import axios from "axios";
import type { AxiosInstance, InternalAxiosRequestConfig } from "axios";
import type { MyRequestConfig } from "./type";
// import { sessionCache } from "@/utils/cache";
// import { LOGIN_TOKEN } from "@/global/constants";

class AxiosRequest {
  instance: AxiosInstance;

  constructor(config: MyRequestConfig) {
    // 创建 Axios 实例，并配置基本信息
    this.instance = axios.create({
      baseURL: config.baseURL, // 设置请求基础URL
      timeout: config.timeout, // 设置请求超时时间
    });

    // 请求拦截器配置
    this.instance.interceptors.request.use(
      (config) => {
        return config;
      },
      (err) => {
        return err;
      }
    );

    // 响应拦截器配置
    this.instance.interceptors.response.use(
      (res) => {
        // 全局
        return res.data;
      },
      (err) => {
        return err;
      }
    );

    // 自定义请求和响应拦截器配置
    this.instance.interceptors.request.use(config.interceptors?.requestSuccessFn, config.interceptors?.requestFailureFn);
    this.instance.interceptors.response.use(config.interceptors?.responseSuccessFn, config.interceptors?.responseFailureFn);
  }

  // 发送请求的方法
  request<T = any>(config: MyRequestConfig<T>) {
    if (config.interceptors?.requestSuccessFn) {
      config = config.interceptors.requestSuccessFn(config as InternalAxiosRequestConfig<any>);
    }

    return new Promise<T>((resolve, reject) => {
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptors?.responseSuccessFn) {
            res = config.interceptors.responseSuccessFn(res);
          }
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }

  // 发送 GET 请求
  get<T = any>(config: MyRequestConfig<T>) {
    return this.request({ ...config, method: "GET" });
  }

  // 发送 POST 请求
  post<T = any>(config: MyRequestConfig<T>) {
    return this.request({ ...config, method: "POST" });
  }

  // 发送 DELETE 请求
  delete<T = any>(config: MyRequestConfig<T>) {
    return this.request({ ...config, method: "DELETE" });
  }

  // 发送 PATCH 请求
  patch<T = any>(config: MyRequestConfig<T>) {
    return this.request({ ...config, method: "PATCH" });
  }

  // 发送 PUT 请求
  put<T = any>(config: MyRequestConfig<T>) {
    return this.request({ ...config, method: "PUT" });
  }
}

export default AxiosRequest;
